const express = require('express')
const path = require('path')
const { WebSocketServer } = require('ws')

const app = express()

app.use(express.static(path.join(__dirname, 'src')))
app.use(express.static(path.join(__dirname, './')))
// websocket
const wss = new WebSocketServer({port: 8080})

// 广播
wss.broadcast = function broadcast(status, userObj={}) {
  var temp = JSON.parse(JSON.stringify(userObj))
  temp.status = status
  temp.count = wss.clients.size
  wss.clients.forEach(function(client) {
    // 广播用户发送信息
    client.send(JSON.stringify(temp))
  })
}
// 建立连接
wss.on('connection', function connection(ws) {
  ws.on('message', function message(msg) {
    var data = JSON.parse(msg)
    this.user = data.user
    wss.broadcast(1, data)
  })
  // 断开连接
  ws.on('close', function close(ws) {
    wss.broadcast(0, {
      code: 500,
      user: this.user
    })
  })
})

app.listen(3000, function(req, res) {
  console.log('打开http://localhost:3000访问页面')
})
